package com.gdpu.liou.symphonyserver.common.exception;

import com.gdpu.liou.symphonyserver.common.utils.LIUUtil;
import com.gdpu.liou.symphonyserver.entity.respose.Response;
import com.gdpu.liou.symphonyserver.entity.respose.ResponseCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;

import static com.gdpu.liou.symphonyserver.common.utils.LIUUtil.getParams;

/**
 * 全局异常捕获
 *
 * @author liuyx
 * @date 2022/5/19 10:18 周四
 */
@Slf4j
@RestController
@RestControllerAdvice
public class ExceptionHandler {

    @org.springframework.web.bind.annotation.ExceptionHandler(value = ResponseException.class)
    public Response<Object> handleResponseException(ResponseException e, HttpServletRequest request) {
        Response<Object> response = new Response<>();
        String ip = request.getRemoteAddr();
        StringBuffer url = request.getRequestURL();
        String method = request.getMethod();
        HashMap<String, String> params = getParams(request);
        log.error("服务器错误!  IP:{}  URL:{}  Method:{}  Params:{}", ip, url, method, params, e);
        response.setCode(e.getResponseCode().getCode());
        response.setMsg(e.getResponseCode().getMessage());
        return response;
    }

    @org.springframework.web.bind.annotation.ExceptionHandler(value = Exception.class)
    public Response<Object> handleException(Exception e, HttpServletRequest request) {
        String ip = request.getRemoteAddr();
        StringBuffer url = request.getRequestURL();
        String method = request.getMethod();
        HashMap<String, String> params = getParams(request);
        log.error("出现未知异常!  IP:{}  URL:{}  Method:{}  Params:{}", ip, url, method, params, e);
        return new Response<>(ResponseCode.SERVER_ERROR);
    }


}
